package com.gome.gop.mybatis;

import java.util.ArrayList;
import java.util.List;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.boot.autoconfigure.MybatisProperties;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.jdbc.DataSourceTransactionManagerAutoConfiguration;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import com.alibaba.druid.pool.DruidDataSource;
import com.gome.gop.config.MybatisConfig;
import com.gome.gop.mybatis.rw.datasource.DynamicDataSourceTransactionManager;
import com.gome.gop.mybatis.rw.datasource.RoutingDataSource;

/**
*
* @author jiangdabin
*/
@Configuration
@EnableTransactionManagement(proxyTargetClass = true)
@ConditionalOnClass({ SqlSessionFactory.class, SqlSessionFactoryBean.class })
@EnableConfigurationProperties({ MybatisProperties.class })
@ConfigurationProperties(prefix = "mybatis.rw")
@Import(MybatisConfig.class)
public class MybatisAutoConfiguration extends DataSourceTransactionManagerAutoConfiguration {
   // 主库数据源
   private List<DruidDataSource> readDataSources = new ArrayList<DruidDataSource>();
   // 写数据源
   private DruidDataSource writeDataSource = new DruidDataSource();
   // 其他数据源，用于手动切换
   private List<DruidDataSource> multiDataSources = new ArrayList<DruidDataSource>();


   @Bean
   public RoutingDataSource dataSource() {
       return new RoutingDataSource(writeDataSource,readDataSources,multiDataSources);
   }

   @Bean(name="transactionManager")
   @ConditionalOnMissingBean
   public DynamicDataSourceTransactionManager transactionManager() {
       DynamicDataSourceTransactionManager dynamicDataSourceTransactionManager = new DynamicDataSourceTransactionManager();
       dynamicDataSourceTransactionManager.setDataSource(this.dataSource());
       return dynamicDataSourceTransactionManager;
   }

   /**
    * @return the writeDataSource
    */
   public DruidDataSource getWriteDataSource() {
       return writeDataSource;
   }
   /**
    * @return the readDataSources
    */
   public List<DruidDataSource> getReadDataSources() {
       return readDataSources;
   }
   /**
    * @return the multiDataSources
    */
   public List<DruidDataSource> getMultiDataSources() {
       return multiDataSources;
   }

}